<template>
  <div class="app-container camp-show-container">
    <!-- 头部标题 -->
    <el-header class="app-header">
      <h1 class="app-title">
        <el-icon class="title-icon"><Calendar /></el-icon>
        活动Camp可视化工具
      </h1>
    </el-header>

    <!-- 主要内容区域 -->
    <el-container class="main-container">
      <!-- 控制面板 -->
      <el-aside width="350px" class="control-panel">
        <el-card class="control-card card-shadow">
          <!-- 区服选择 -->
          <ServerSelector 
            v-model:selectedServers="selectedServers"
            :servers="allServers"
            :loading="serversLoading"
            @refresh="loadServerData"
          />
          
          <!-- 时间范围选择 -->
          <TimeRangeSelector 
            v-model:startTime="startTime"
            v-model:endTime="endTime"
          />
          
          <!-- 刷新按钮 -->
          <div class="refresh-section">
            <el-button 
              type="primary" 
              size="large"
              :loading="campDataLoading"
              @click="refreshCampData"
              class="refresh-btn"
            >
              <el-icon><Refresh /></el-icon>
              刷新活动数据
            </el-button>
          </div>
        </el-card>
      </el-aside>

      <!-- 图表区域 -->
      <el-main class="chart-container">
        <el-card class="chart-card card-shadow">
          <ActivityTimeline 
            :campData="campData"
            :selectedServers="selectedServers"
            :startTime="startTime"
            :endTime="endTime"
            :loading="campDataLoading"
            @refresh="refreshCampData"
            @activity-click="handleActivityClick"
          />
        </el-card>
      </el-main>
    </el-container>

    <!-- 状态栏 -->
    <el-footer height="40px" class="status-bar">
      <div class="status-left">
        <el-text class="status-text">{{ statusMessage }}</el-text>
      </div>
      <div class="status-right">
        <el-tag 
          v-if="networkStatus" 
          :type="networkStatus.type" 
          size="small"
          class="network-status"
        >
          <el-icon><Connection /></el-icon>
          {{ networkStatus.text }}
        </el-tag>
      </div>
    </el-footer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { logger } from './utils/logger.ts'
import { ElMessage } from 'element-plus'
import { Calendar, Refresh, Connection } from '@element-plus/icons-vue'
import ServerSelector from './ServerSelector.vue'
import TimeRangeSelector from './TimeRangeSelector.vue'
import ActivityTimeline from './ActivityTimeline.vue'
import { serverApi, campApi } from './api/index.ts'
import { parseErlangTerm, convertToCampList } from './utils/dataParser.ts'
import './camp-show.css'

// 响应式数据
const allServers = ref<any[]>([])
const selectedServers = ref<any[]>([])
const startTime = ref<Date | null>(null)
const endTime = ref<Date | null>(null)
const campData = ref<any[]>([])
const serversLoading = ref(false)
const campDataLoading = ref(false)
const statusMessage = ref('准备就绪，请等待服务器列表加载完成后手动刷新活动数据')
const networkStatus = ref<{type: string, text: string} | null>(null)

// 加载服务器数据
const loadServerData = async () => {
  serversLoading.value = true
  statusMessage.value = '正在加载服务器列表...'
  
  try {
    const result = await serverApi.getServerList()
    
    let servers = []
    let isFromFallback = false
    let originalError = null
    
    // 处理新的API响应格式
    if (Array.isArray(result)) {
      // 直接返回的服务器数组
      servers = result
    } else if (result && typeof result === 'object') {
      // 包含备用数据信息的对象
      servers = result.servers || []
      isFromFallback = result.isFromFallback || false
      originalError = result.originalError
    }
    
    if (servers.length === 0) {
      throw new Error('未获取到任何服务器数据')
    }
    
    // 按开服时间排序，取最新的6个作为默认选中
    servers.sort((a: any, b: any) => parseInt(b.open_time || 0) - parseInt(a.open_time || 0))
    allServers.value = servers
    selectedServers.value = servers.slice(0, 6)
    
    // 根据数据来源显示不同的状态消息
    if (isFromFallback) {
      statusMessage.value = `使用备用服务器列表，共 ${servers.length} 个区服。请点击"刷新活动数据"按钮获取活动信息。（原始错误: ${originalError}）`
      networkStatus.value = { type: 'warning', text: '备用模式' }
      ElMessage.warning({
        message: '远程服务器列表获取失败，已切换到备用列表。请手动刷新活动数据。',
        duration: 5000,
        showClose: true
      })
    } else {
      statusMessage.value = `服务器列表加载完成，共 ${servers.length} 个区服。请点击"刷新活动数据"按钮获取活动信息。`
      networkStatus.value = { type: 'success', text: '在线' }
      ElMessage.success('服务器列表加载成功，请手动刷新活动数据')
    }
    
    // 不再自动刷新活动数据，需要用户手动点击刷新按钮
    
  } catch (error: any) {
    console.error('加载服务器列表失败:', error)
    statusMessage.value = `加载失败: ${error.message}`
    networkStatus.value = { type: 'danger', text: '离线' }
    
    // 提供更详细的错误信息和解决建议
    let errorMessage = '服务器列表加载失败'
    let suggestion = ''
    
    if (error.message.includes('Network Error') || error.message.includes('timeout')) {
      errorMessage = '网络连接失败'
      suggestion = '请检查网络连接后重试'
    } else if (error.message.includes('CORS')) {
      errorMessage = '跨域请求被阻止'
      suggestion = '请联系管理员配置服务器'
    } else {
      errorMessage = error.message
      suggestion = '请稍后重试或联系技术支持'
    }
    
    ElMessage.error({
      message: `${errorMessage}。${suggestion}`,
      duration: 8000,
      showClose: true
    })
  } finally {
    serversLoading.value = false
  }
}

// 刷新活动数据
const refreshCampData = async () => {
  if (!selectedServers.value.length) {
    ElMessage.warning('请至少选择一个区服')
    return
  }
  
  if (!startTime.value || !endTime.value) {
    ElMessage.warning('请选择时间范围')
    return
  }
  
  campDataLoading.value = true
  statusMessage.value = '正在加载活动数据...'
  
  try {
    // 构建请求参数
    const pzoList = selectedServers.value.map((server: any) => 
      `${server.platform}_${server.zone_id}_${server.open_time}`
    ).join(',')
    
    const startTimestamp = Math.floor(startTime.value!.getTime() / 1000)
    const endTimestamp = Math.floor(endTime.value!.getTime() / 1000)
    
    const result = await campApi.getCampData(pzoList, startTimestamp, endTimestamp)
    
    // 解析数据
    let parsedData = []
    logger.debug('🔍 [数据解析] 开始解析活动数据:', { 
      数据类型: typeof result, 
      是否数组: Array.isArray(result),
      是否对象: typeof result === 'object',
      数据长度: typeof result === 'string' ? result.length : (Array.isArray(result) ? result.length : '对象'),
      数据预览: typeof result === 'object' ? result : (typeof result === 'string' ? result.substring(0, 100) + '...' : result)
    })
    
    // 统一使用parseErlangTerm处理所有数据格式（现在支持JSON和Erlang格式）
    statusMessage.value = '正在解析活动数据...'
    logger.debug('📝 [数据解析] 调用统一解析器...')
    parsedData = parseErlangTerm(result)
    logger.debug('🏗️ [数据解析] 解析结果:', parsedData)
    
    campData.value = convertToCampList(parsedData)
    logger.debug('📋 [数据解析] 最终活动列表:', campData.value)
    
    // 验证解析结果
    logger.debug('🎯 [数据验证] 解析完成:', {
      活动总数: campData.value.length,
      服务器分布: campData.value.reduce((acc: any, camp: any) => {
        acc[camp.server] = (acc[camp.server] || 0) + 1
        return acc
      }, {}),
      时间范围: campData.value.length > 0 ? {
        最早: new Date(Math.min(...campData.value.map((c: any) => c.start_time)) * 1000).toLocaleString('zh-CN'),
        最晚: new Date(Math.max(...campData.value.map((c: any) => c.end_time)) * 1000).toLocaleString('zh-CN')
      } : '无数据'
    })
    
    // 过滤超过60天的活动
    const filteredData = campData.value.filter((camp: any) => {
      const duration = (camp.end_time - camp.start_time) / 86400
      return duration <= 60
    })
    
    const filteredCount = campData.value.length - filteredData.length
    campData.value = filteredData
    
    let message = `活动数据加载完成，共 ${filteredData.length} 条活动`
    if (filteredCount > 0) {
      message += `（已过滤 ${filteredCount} 条超过60天的活动）`
    }
    
    statusMessage.value = message
    ElMessage.success('活动数据加载成功')
    
  } catch (error: any) {
    console.error('加载活动数据失败:', error)
    statusMessage.value = `加载失败: ${error.message}`
    ElMessage.error(`加载活动数据失败: ${error.message}`)
    campData.value = []
  } finally {
    campDataLoading.value = false
  }
}

// 处理活动点击事件
const handleActivityClick = (activity: any) => {
  logger.debug('🎯 [活动点击]', activity)
  ElMessage.info({
    message: `活动详情: ${activity.camp_name}`,
    duration: 3000
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadServerData()
})
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-header {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.app-title {
  color: #ffffff;
  font-size: 24px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 28px;
  color: #409eff;
}

.main-container {
  flex: 1;
  padding: 20px;
  gap: 20px;
}

.control-panel {
  background: transparent;
}

.control-card {
  background: rgba(45, 45, 45, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.refresh-section {
  margin-top: 20px;
  text-align: center;
}

.refresh-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
}

.chart-container {
  padding: 0;
}

.chart-card {
  height: calc(100vh - 200px);
  background: rgba(30, 30, 30, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow-y: auto;
}

.status-bar {
  background: #2d2d2d;
  border-top: 1px solid #444;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.status-left {
  display: flex;
  align-items: center;
}

.status-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-text {
  color: #ccc;
  font-size: 14px;
}

.network-status {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-container {
    flex-direction: column;
  }
  
  .control-panel {
    width: 100% !important;
  }
  
  .chart-card {
    height: 600px;
  }
}
</style>
